package com.rancedxk.monitor;

import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.kit.PropKit;
import com.jfinal.template.Engine;
import com.rancedxk.monitor.controller.ApiController;
import com.rancedxk.monitor.controller.LiveController;
import com.rancedxk.monitor.controller.ProcessController;
import com.rancedxk.monitor.device.DeviceManager;
import com.rancedxk.monitor.device.provider.IDeviceProvider;
import com.rancedxk.monitor.utils.F;
import com.rancedxk.monitor.utils.H;
import com.rancedxk.monitor.utils.N;

public class Config extends JFinalConfig{
	public static final String PROJECT_PATH = System.getProperty("user.dir").replaceAll("\\\\", "/");

	@Override
	public void configConstant(Constants me) {
		me.setDevMode(true);
	}

	@Override
	public void configRoute(Routes me) {
		me.setBaseViewPath("/page");
		me.add("/live",LiveController.class);
		me.add("/process",ProcessController.class);
		me.add("/api",ApiController.class);
	}

	@Override
	public void configEngine(Engine me) {
	}

	@Override
	public void configPlugin(Plugins me) {
	}

	@Override
	public void configInterceptor(Interceptors me) {
	}

	@Override
	public void configHandler(Handlers me) {
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public void afterJFinalStart() {
		//0.设置监控设备管理器
		if(PropKit.containsKey("device.provider")){
			String deviceProviderClass = PropKit.get("device.provider");
			try {
				Class clazz = Class.forName(deviceProviderClass);
				Object instance = clazz.newInstance();
				if(instance instanceof IDeviceProvider){
					DeviceManager.setProvider((IDeviceProvider)instance);
				}
			} catch (Exception e) {
				throw new RuntimeException("加载监控设备管理器失败，请检查配置或使用默认加载方式[com.rancedxk.monitor.device.provider.impl.DefaultProvider]");
			}
		}

		//1.初始化启动Nginx
		try {
			//关闭Nginx
			N.stop();
			//同步配置信息
			N.config();
			//启动Nginx
			N.start();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("启动Nginx失败");
		}

		//2.初始化创建HLS路径
		H.initHome();

		//3.关闭所有ffmpeg进程
		try {
			F.stop();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("关闭ffmpeg进程失败");
		}
	}
}
